import { _decorator, Component, Node, Size, size, UITransform, v3, Vec3, view } from 'cc';
import EventManager from '../../Init/Managers/EventManager';
import { EventTypes } from '../../Init/Managers/EventTypes';
import { GlobalEnum } from '../../Init/Config/GlobalEnum';

const { ccclass, property } = _decorator;
// 微信截屏分享区域 
@ccclass('WxShareArea')
export class WxShareArea extends Component {
    // 5：4 分享区域
    @property(Node)
    shareArea: Node = null;

    _wpos: Vec3 = v3();
    _size: Size = size(0, 0);
    protected onLoad(): void {
        this.shareArea = this.shareArea || this.node;
    }


    protected onEnable(): void {
        this._size.set(this.shareArea.getComponent(UITransform).contentSize);
        this._wpos.set(this.shareArea.worldPosition);
        // console.log('# onEnable', this._wpos, this._size);
    }
    setAreaWpos(_wpos: Vec3) {
        this.shareArea.setWorldPosition(_wpos);
        this._wpos.set(_wpos);
    }
    setAreaSize(_size: Size,) {
        this.shareArea.getComponent(UITransform).setContentSize(_size);
        this._size.set(_size);
    }

    // 用于主动分享
    onShare(title: string, urlType: GlobalEnum.SharePosition, success?: Function, fail?: Function) {

        // 计算分享截屏位置范围
        let _cvsSize = view.getVisibleSize();

        console.log('# onShare', this._size, _cvsSize);

        // 获取左上角位置
        let _pos = v3();
        _pos.x = this._wpos.x - this._size.width * 0.5;
        _pos.y = _cvsSize.height - (this._size.height * 0.5 + this._wpos.y);
        // 计算相对比例
        _pos.x = _pos.x / _cvsSize.width;
        _pos.y = _pos.y / _cvsSize.height;
        this._size.width /= _cvsSize.width;
        this._size.height /= _cvsSize.height;

        EventManager.emit(EventTypes.SDKEvents.Share, {
            title: title, pos: _pos,
            urlType: urlType, size: this._size,
            success: success, fail: () => {
                EventManager.emit(EventTypes.GameEvents.ShowTips, '分享失败,稍后再试!');
            }
        });
    }
}

